package cn.wolfcode.rbac.service.Impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.qo.RoleQo;
import cn.wolfcode.rbac.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xiahuihui
 * #Description RoleImpl
 * #Date: 2022/7/2 13:49
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Role> findRoleAll() {

        List<Role> roles = roleMapper.selectAll();
        return roles;
    }

    @Override
    public PageInfo<Role> findByPage(RoleQo qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());

        List<Role> roles = roleMapper.selectByCondition(qo);

        return new PageInfo<Role>(roles);
    }

    @Override
    public List<Permission> findPermissionAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public void save(Role role, Long[] permissionIds) {

        if(role.getId() == null){
            roleMapper.insert(role);
        }else{
            roleMapper.updateByPrimaryKey(role);
            roleMapper.deleteRole(role.getId());
        }
        if(permissionIds != null){
            //遍历出每一个角色id
            for(Long permissionId : permissionIds){
                //关联保存员工角色信息
                roleMapper.insertRolePermission(role.getId(),permissionId);
            }
        }
    }

    @Override
    public void delete(Role role) {
        roleMapper.deleteByPrimaryKey(role.getId());
        roleMapper.deleteRolePermission(role.getId());
    }

    @Override
    public Role findById(Long id) {
        return roleMapper.findone(id);
    }
}